package com.firemoss.magicbus.messaging
{
	import com.firemoss.magicbus.messaging.fillter.BeforeFilterChain;
	
	import mx.messaging.Producer;
	import mx.messaging.messages.IMessage;

	/**
	 *  You shouldn't have to be an expert in Flex messaging to use it.  
	 *  <p>
	 * 	The ProducerMediator simplifies using a producer.  You don't have to construct
	 *  Flex AsyncMessages or any of that:  just dispatch an appropriate event and its data will
	 *  be sent out over the producer/  
	 *  <p>
	 *  In its simplest use,
	 *  you just state what event name the producer should listen for and what property of
	 *  the event contains the data to be sent.  
	 *  </p><p>
	 *  For example, if you had a ChatEvent of type MESSAGE_SENT, and that event had a property
	 *  of "message" containing the message, this is all you'd need to do:
	 *  </p><p>
	 *  &lt;messaging:ProducerMediator consumer="{ chatProducer }" messageSendEvent="{ ChatEvent.MESSAGE_SENT }" bodyProperty="message" /&gt;
	 *  </p><p>
	 * 
	 *  Then, just created a bubbled UI event of type MESSAGE_SENT (Swiz mediation works!) or dispatch a MESSAGE_SENT event via Swiz.dispatchEvent()!
	 */	
	public class AbstractProducerMediator extends AbstractMessageAgentMediator implements IProducerMediator
	{
		// PUBLIC PROPERTIES
		
		public var clientId : String
		
		public var messageConverter : IProducerMessageConverter
		
		public var beforeChain : BeforeFilterChain

		public function set beforeFilters( value : Object ) : void
		{
			if ( !value ) return
			
			if ( !( value is Array ) ) { value = [ value ] }
			
			beforeChain = new BeforeFilterChain( value as Array )
		}
		
		public function set messageSentEvents( eventNames : Array ) : void
		{
			subscribeToMessageSentEvents( eventNames )
		}
		
		public function set producer( producer : Producer ) : void
		{
			super.messageAgent = producer
		}
		public function get producer() : Producer
		{
			return super.messageAgent as Producer
		}
		
		public function AbstractProducerMediator()
		{
			messageConverter = new DefaultProducerMessageConverter( this )

			converter = messageConverter
		}
		
		// IProducerMediator stubs
		
		public function subscribeToMessageSentEvents( eventNames : Array ) : void
		{
			// NO-OP:  implement in subclasses!
		}
		
		// NOTIFICATION LISTENERS
		
		protected function messageSent( event : Object ) : void
		{
			if ( messageConverter )
			{
				var message : IMessage = messageConverter.convert( this, event )
				
				if ( message && producer )
				{
					if ( beforeChain )
					{
						beforeChain.execute( [ message ] )
					}
					
					producer.send( message )
				}
			}
		}
		
	}
}